﻿using System;
using System.Diagnostics;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Content;
using Microsoft.Xna.Framework.Graphics;
using Microsoft.Xna.Framework.Input.Touch;
using GauntletFramework.Input;
using System.Threading;

namespace GauntletFramework.StateManagment.Loading
{
    public class StatePause : State
    {
        public StatePause(State ParentState)
        {
            if (PauseFont == null)
                PauseFont = Game.Content.Load<SpriteFont>(@"GauntletBase\PauseFont");
            this.ParentState = ParentState;
            BasicInput bi = StaticGame.BasicInput;

            OldPIS = bi.PhoneInputState;
        }

        public override bool StartTransition { get { return false; } }
        public override bool EndTransition { get { return false; } }

        PhoneInputState OldPIS;

        protected static SpriteFont PauseFont = null;
        public State ParentState;

        float FadeValue = 0.0f;
        bool FadeIn = true;
        bool FadeOut = false;

        public override void Update(GameTime gameTime)
        {
            base.Update(gameTime);

            BasicInput bi = StaticGame.BasicInput;

            if (FadeIn)
                FadeValue += (float)gameTime.ElapsedGameTime.TotalSeconds * 5.0f;

            if (FadeOut)
                FadeValue -= (float)gameTime.ElapsedGameTime.TotalSeconds * 5.0f;
            
            if (FadeValue < 0.0f) 
            { 
                FadeValue = 0.0f;
                StaticGame.StateStack.PopState();
            }
            if (FadeValue > 0.5f) 
            { 
                FadeValue = 0.5f; 
                FadeIn = false;
                bi.PhoneInputState = OldPIS;
                bi.PhoneInputState = PhoneInputState.PhoneControlPauseAuto;
            }

            if (bi.ActionPause == AdvancedButtonState.Released) 
            {
                FadeOut = true;
                bi.PhoneInputState = PhoneInputState.PhoneControlNone;
            }
            if (bi.ButtonBack == AdvancedButtonState.Released)
            {
                FadeOut = true;
                bi.PhoneInputState = PhoneInputState.PhoneControlNone;
                ParentState.Finished = true;
            }
        }

        public override void Draw(GameTime gameTime)
        {
            base.Draw(gameTime);

            ParentState.Draw(gameTime);

            SpriteBatch sb = StaticGame.SpriteBatch;

            sb.Draw(StaticGame.Game.MonoColor, StaticGame.ScreenSize, new Color(0.0f, 0.0f, 0.0f, FadeValue));
            sb.DrawString(PauseFont, "PAUSED", StaticGame.ScreenCenter - PauseFont.MeasureString("PAUSED") / 2.0f, new Color(FadeValue * 2f, FadeValue * 2f, FadeValue * 2f, FadeValue * 2f));
        }
    }
}
